package services

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/url"
	"strings"

	"boomlive.com/boomlive-common/configs"
	"boomlive.com/boomlive-common/constants"
	"github.com/beego/beego/v2/core/logs"
	"github.com/dromara/dongle"
)

//type ExtParams struct {
//	UserID    string `json:"userId"`
//	PkgName   string `json:"pkgName"`
//	SJchannel int    `json:"sjchannel"`
//	GID       int    `json:"gId"`
//	Gamemode  int    `json:"gamemode"`
//	RoomId    int    `json:"roomId"`
//	AnchorID  int    `json:"anchorID"`
//}

type JoyPlayUserInfo struct {
	UserId         string `json:"userId"`
	PkgName        string `json:"pkgName"`
	Nickname       string `json:"nickname"`
	AvatarUrl      string `json:"avatarUrl"`
	AvailableCoins int64  `json:"availableCoins"`
	Level          int    `json:"level"`
}

type JoyPlayTradeInfo struct {
	GId           int     `json:"gId"`
	SJchannel     int     `json:"sjchannel"`
	TransactionId string  `json:"transactionId"`
	Useridx       string  `json:"useridx"`
	AgentTxid     string  `json:"agentTxid"`
	BetAmount     float64 `json:"betAmount"`
	WinAmount     float64 `json:"winAmount"`
	RoomId        int     `json:"roomId"`
	AnchorID      int     `json:"anchorID"`
}

func HandleJoyplayAuthorization(authHeader string) (string, constants.ErrNo) {
	if authHeader == "" {
		return "", constants.ERR_JOYPLAY_AUTH_HEADER_REQUIRED
	}

	token := strings.TrimPrefix(authHeader, "Bearer ")
	if token == "" {
		return "", constants.ERR_JOYPLAY_AUTH_HEADER_FORMAT
	}
	return token, constants.SUCCESS
}

type ExtParams struct {
	UserID   string `json:"user_id"`
	Token    string `json:"token"`
	GameId   string `json:"gameid"`
	AnchorID string `json:"anchorid"`
	PkgName  string `json:"pkgName"`
}

// ParseExtParam 解码 ext 参数并映射到结构体
func ParseExtParam(ext string) (*ExtParams, error) {

	// 第一步：URL 解码
	decodedUrl, err := url.QueryUnescape(ext)
	if err != nil {
		return nil, fmt.Errorf("URL 解码失败: %w", err)
	}
	logs.Info("ext url QueryUnescape result: decodedUrl=%s", decodedUrl)

	// 第二步：Base64 解码
	paramStr, err := base64.StdEncoding.DecodeString(decodedUrl)
	if err != nil {
		return nil, fmt.Errorf("Base64 解码失败: %w", err)
	}

	// 第三步：解析为 URL 参数对
	values, err := url.ParseQuery(string(paramStr))
	if err != nil {
		return nil, fmt.Errorf("参数解析失败: %w", err)
	}
	logs.Info("ext url ParseQuery result: values=%v", values)

	extParams := &ExtParams{
		UserID:   values.Get("user_id"),
		GameId:   values.Get("gameid"),
		Token:    values.Get("token"),
		AnchorID: values.Get("anchorid"),
		PkgName:  values.Get("pkgName"),
	}

	return extParams, nil
}

func DecryptData(encryptedHex string) ([]byte, error) {
	// 1. 读取私钥（从环境变量或安全存储）
	privateKey, err := getPrivateKey() // 实现你的密钥获取逻辑
	if err != nil {
		logs.Error("获取私钥失败: %s", err.Error())
		return nil, err
	}

	// 2. 解密流程
	ddData := dongle.Decrypt.FromHexBytes([]byte(encryptedHex)).ByRsa([]byte(privateKey)).ToBytes()

	return ddData, nil
}

type KiwiSubmitFlowRequest struct {
	Coin     int64  `json:"coin"`
	Gameid   string `json:"gameid"`
	Token    string `json:"token"`
	Linkid   string `json:"linkid"`
	AnchorID string `json:"anchorid"`
	UserID   string `json:"user_id"`
	Ext      string `json:"ext"`
}

type KiwiSubmitFlowResponse struct {
	RestMoney int64  `json:"rest_money"`
	Code      string `json:"code"`
	Uid       int64  `json:"uid"`
	Linkid    string `json:"linkid"`
	Result    bool   `json:"result"`
	Dt        int64  `json:"dt"`
	Msg       string `json:"msg"`
}

func KiwiSubmitFlow(req *KiwiSubmitFlowRequest) (resp *KiwiSubmitFlowResponse, err error) {
	submitUrl := configs.KiwiSubmitUrl
	headers := map[string]string{
		"Content-Type": "application/json",
	}
	submitUrl = submitUrl + "?" + "coin=" + fmt.Sprintf("%d", req.Coin) + "&gameid=" + req.Gameid + "&token=" + req.Token + "&linkid=" + req.Linkid + "&anchorid=" + req.AnchorID + "&user_id=" + req.UserID + "&ext=" + req.Ext
	respBody, errH := HttpCall("GET", submitUrl, headers, nil)
	if errH != nil {
		logs.Error("请求加扣币url:%s 失败:%s", submitUrl, errH.Error())
		return nil, errH
	}
	logs.Debug("响应体数据:%s", string(respBody))

	var submitResp KiwiSubmitFlowResponse
	err = json.Unmarshal(respBody, &submitResp)
	if err != nil {
		logs.Error("解析Kiwi接口响应数据失败: %v", err)
		return nil, err
	}
	logs.Debug("Kiwi接口响应数据:%v", submitResp)

	return &submitResp, nil
}

func getPrivateKey() (string, error) {
	key := configs.JoyplayPrivateKey
	if key == "" {
		return "", fmt.Errorf("私钥为空")
	}
	return key, nil
}
